import axios from "axios"
import router from "@/router";

const instance = axios.create({
    baseURL: "http://localhost:8080",
    timeout: 5000,
})

instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem("token");
        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)

instance.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if(error.response.status === 401) {
            localStorage.removeItem("token");
            router.push("/login").then(
                result => {
                    return result
                }
            )
        }
        return Promise.reject(error);
    }
)

export const getAction = (url, data, flag) => {
    return instance({
        url,
        method: "GET",
        data
    })
}

export const postAction = (url, data, flag) => {
    return instance({
        url,
        method: "POST",
        data
    })
}

export const putAction = (url, data, flag) => {
    return instance({
        url,
        method: "PUT",
        data
    })
}

export const deleteAction = (url, data, flag) => {
    return instance({
        url,
        method: "DELETE",
        data
    })
}

export default instance;